import React ,{useState,useRef,useEffect}from "react";
import { Button, Modal,Form,Input, message,Select, Upload,InputNumber} from "antd";
import {removeSysFile } from '@/services/ant-design-pro/apis';
const FormItem = Form.Item;

const { TextArea } = Input;
const { Option } = Select;
import { UploadOutlined,PlusOutlined, } from '@ant-design/icons';
import { ProFormUploadButton } from '@ant-design/pro-form';
const { Dragger } = Upload;

const CreateBank = (props) => {
    const tokent = localStorage.getItem('token');
    const token = tokent == undefined ? '' : tokent;
    const [fileList, setFileList] = useState([]);
    const [archivesValue, setArchivesValue] = useState('');

    

    const handleUpload = async ({ onSuccess, onError, file }) => {
        try {
          const uploadFile = async (file) => {
            const formData = new FormData();
            formData.append('uploadfile', file);
            const response = await fetch('/api/upLoad', {
              method: 'POST',
              body: formData,
              headers: {
                'access-control-allow-origin': '*',
                token: token,
              },
            });
            const newResponse = await response.json();
            if (newResponse && newResponse.data) {
              const path = newResponse.data;
              // 更新archivesValue，包含新上传的文件路径
              setArchivesValue((prevValue) => {
                const paths = prevValue ? prevValue.split(',') : [];
                paths.push(path);
                return paths.join(',');
              });
              onSuccess(path, file);
            } else {
              throw new Error('上传失败或返回的数据格式不正确');
            }
          };
          await uploadFile(file);
        } catch (error) {
          console.error(error);
          onError(error, file);
          message.error('文件上传失败');
        }
      };
    
      const handleChange = ({ fileList: newFileList }) => {
        // 使用beforeUpload来过滤文件
        const filteredFileList = newFileList.filter((file) => beforeUpload(file));
        console.log(archivesValue);
        setFileList(filteredFileList.length > 0 ? filteredFileList : fileList);
      };
    
      const handleRemove = (file) => {
        const index = fileList.indexOf(file);
    
        if (index === -1) {
          console.error('文件不在列表中');
          return;
        }
    
        const paths = archivesValue.split(',');
        const element = paths[index];
        const fileName = element.split('/').pop().split('\\').pop(); // 提取文件名
    
        const removeFile = async () => {
          const hide = message.loading('正在删除');
          try {
            await removeSysFile(fileName);
            hide();
            const newFileList = fileList.slice();
            newFileList.splice(index, 1);
            setFileList(newFileList);
    
            setArchivesValue((prevValue) => {
              const paths = archivesValue.split(',');
              if (index !== -1) {
                paths.splice(index, 1);
              }
              if (paths.index !== -1) {
                return paths.join(',');
              } else {
                setArchivesValue(undefined);
              }
            });
            message.success('删除成功');
          } catch {
            hide();
            message.error('删除失败');
          }
        };
        removeFile();
      };
    
      const beforeUpload = (file) => {
        // 阻止自动上传，如果需要的话，你可以在这里处理图片上传逻辑
        const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJPGorPNG) {
          message.error('只能上传 JPG 或 PNG 格式图片!');
          return false;
        }
        const isLt10K = file.size < 300 * 1024;
        if (!isLt10K) {
          message.error('图片大小不能超过 300KB!');
          return false;
        }
        return true;
      };
    

    const formLayout = {
        labelCol: {
            span: 5,
        },
        wrapperCol: {
            span: 15,
        },
    };

    const [formVals, setFormVals] = useState({})

    const channels=props.channels;

  const { onSubmit: handCreate, onCancel: handleModalVisible, createModalVisible } = props;
    const handleSubmit = async () => {
        try {
            const fieldVlas = await form.validateFields();
            fieldVlas.img = archivesValue;
            handCreate({ ...fieldVlas })
            onReset()
        } catch (err) {
            console.log(err)
        }
    }

    const onReset = () => {
        form.resetFields();
    }


    const [form] = Form.useForm();


    return (
        <Modal
            title="新建轮播图"
            width={540}
            visible={createModalVisible}
            destroyOnClose
            onCancel={() => {
                onReset();
                handleModalVisible(false)
            }}
            footer={[
                <Button key="reset" onClick={onReset}>重置</Button>,
                <Button type="primary" key="submit" onClick={() => { handleSubmit() }}>提交</Button>
            ]}
        >
            <Form
              {...formLayout}
              initialValues={
                  {
                    apiStatus:2,
                  }
              }
              form={form}
            >
                <FormItem
                  label="名称"
                  name="name"
                  rules={[{
                      required:true,
                      message:'名称是必须项'
                  }]}
                >
                    <Input placeholder="请输入名称"></Input>
                </FormItem>
                <FormItem label="排序值" name="sort">
                <InputNumber   style={{ width: '100%' }}

            placeholder="请输入排序值(值越大越靠前)"
          />
                </FormItem>
                <Form.Item
          label="轮播图"
          name="img"
          initialValue={archivesValue} // 设置初始值
        >
          <Upload
            action="" // 替换为你的实际图片上传接口地址
            listType="picture-card"
            fileList={fileList}
            //onPreview={handlePreview}
            onChange={handleChange}
            beforeUpload={beforeUpload}
            onRemove={handleRemove}
            customRequest={handleUpload}
          >
            {fileList.length < 1 && (
              <div>
                <button style={{ border: 0, background: 'none' }} type="button">
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>上传图片</div>
    </button>

              </div>
            )}
          </Upload>
        </Form.Item>

            </Form>
        </Modal>
    )
}

export default CreateBank;